﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Collections;

namespace KP_CommonLibrary.KP_Function
{
    public static class ArgsParser
    {
        /// <summary>
        /// /KeyName1=Value1 /KeyName=Value2 .... /KeyNamen=Valuen
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static Dictionary<string, string> Parse1(string input)
        {
            string[] allKeyAndValue = input.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            Dictionary<string, string> temp = new Dictionary<string, string>();
            int i = 0;
            string node = "unknown";
            try
            {
                for (i = 0; i < allKeyAndValue.Length; i++)
                {
                    node = allKeyAndValue[i];
                    if (node.IndexOf('=') > 0)
                    {
                        string[] arr = node.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                        if (arr.Length > 1)
                        {
                            temp.Add(arr[0], arr[1]);
                        }
                        else
                            throw new Exception(node + "\nCấu trúc tham số không đúng\n/KeyName1=Value1 /KeyName=Value2 .... /KeyNamen=Valuen");
                    }
                    else
                        throw new Exception(node + "\nCấu trúc tham số không đúng\n/KeyName1=Value1 /KeyName=Value2 .... /KeyNamen=Valuen");

                }
            }
            catch (Exception ex)
            {
                throw new Exception("Lỗi khi phân tích tham số\nData:" + input + "\nIndex:" + i.ToString() + "\tNode:" + node + "\n" + ex.Message, ex);

            }
            return temp;
        }

        public static string[] Parse2(string str)
        {
            if (str == null || !(str.Length > 0)) return new string[0];
            int idx = str.Trim().IndexOf(" ");
            if (idx == -1) return new string[] { str };
            int count = str.Length;
            ArrayList list = new ArrayList();
            while (count > 0)
            {
                if (str[0] == '"')
                {
                    int temp = str.IndexOf("\"", 1, str.Length - 1);
                    while (str[temp - 1] == '\\')
                    {
                        temp = str.IndexOf("\"", temp + 1, str.Length - temp - 1);
                    }
                    idx = temp + 1;
                }
                if (str[0] == '\'')
                {
                    int temp = str.IndexOf("\'", 1, str.Length - 1);
                    while (str[temp - 1] == '\\')
                    {
                        temp = str.IndexOf("\'", temp + 1, str.Length - temp - 1);
                    }
                    idx = temp + 1;
                }
                string s = str.Substring(0, idx);
                int left = count - idx;
                str = str.Substring(idx, left).Trim();
                list.Add(s.Trim('"'));
                count = str.Length;
                idx = str.IndexOf(" ");
                if (idx == -1)
                {
                    string add = str.Trim('"', ' ');
                    if (add.Length > 0)
                    {
                        list.Add(add);
                    }
                    break;
                }
            }
            return (string[])list.ToArray(typeof(string));
        }
        [DllImport("shell32.dll", SetLastError = true)]
        static extern IntPtr CommandLineToArgvW(
            [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);

        public static string[] CommandLineToArgs(string commandLine)
        {
            int argc;
            IntPtr argv = CommandLineToArgvW(commandLine, out argc);
            if (argv == IntPtr.Zero)
                throw new System.ComponentModel.Win32Exception();
            try
            {
                string[] args = new string[argc];
                for (int i = 0; i < args.Length; i++)
                {
                    IntPtr p = Marshal.ReadIntPtr(argv, i * IntPtr.Size);
                    args[i] = Marshal.PtrToStringUni(p);
                }

                return args;
            }
            finally
            {
                Marshal.FreeHGlobal(argv);
            }
        }
    }

}
